export default class TimelineEvent {
  $container;
  $scroller;
  $timeline;
  // 速度增量阈值
  #speed = 30;
  // 截流函数，时间戳
  #timestamp = 0;
  // 截流函数，时间间隔
  #interval = 50;
  // 最大移动距离
  #maxScroll;
  // 当前移动距离
  #moveX = 0;
  // 开始坐标
  #startX = 0;
  // 结束位置
  #endX;
  constructor({ width, $timeline, $scroller, $container, onTimelineScroll }) {
    this.#maxScroll = $container.width() - width;
    this.$container = $container;
    this.$scroller = $scroller;
    this.$timeline = $timeline;
    // console.log($container.width(), width)
    this.onTimelineScroll = onTimelineScroll;
    this.bindEvent()
  }

  /**
   * 对外暴露接口
   *
   * @param arg
   */
  onTimelineScroll = (arg) => {}

  /**
   * 【鼠标按下】
   * todo 记录开始位置，已移动距离
   */
  onMouseDown = (event) => {
    const left = $(event.target).closest('.time-timeline').css('left');
    event.stopPropagation();
    this.#startX = event.pageX;
    this.#timestamp = Date.now();
    this.#moveX = +parseInt(left);
    this.bindMouseMove();
  }

  /**
   * 计算滚动距离
   *
   * @param event
   */
  onScrollMove = (event) => {
    const speed = event.pageX - this.#startX;
    this.#moveX += speed * this.#speed / 100;
    if (this.#moveX > 0) this.#moveX = 0;
    if (this.#moveX < this.#maxScroll) this.#moveX = this.#maxScroll;
    this.onTimelineScroll(this.#moveX);
  }

  /**
   * 鼠标移动时
   *
   * @param event
   */
  onMouseMove = (event) => {
    if (event.which && event.which !== 3) {
      if (Date.now() - this.#timestamp > this.#interval) {
        this.onScrollMove(event);
        this.#timestamp = Date.now();
      }
    } else {
      this.offMouseMove()
    }
  }

  /**
   * 结束移动
   * @param event
   */
  onMouseUp = (event) => {
    this.#endX = event.pageX
    this.#timestamp = 0;
    this.onScrollMove(event)
    this.offMouseMove()
  }

  /**
   * 清理事件
   */
  offMouseMove = () => {
    $(document)
        .off('mousemove', this.onMouseMove)
    $(document)
        .off('mouseup', this.onMouseUp)
  }

  /**
   * 绑定移动事件
   */
  bindMouseMove = () => {
    $(document)
        .off('mousemove', this.onMouseMove)
        .on('mousemove', this.onMouseMove)
    $(document)
        .off('mouseup', this.onMouseUp)
        .on('mouseup', this.onMouseUp)
  }

  // 销毁 - 接触事件
  off = () => {
    this.$timeline.off('mousedown', this.onMouseDown)
    this.offMouseMove()
  }

  /**
   * 为时间轴绑定时间【鼠标按下】
   */
  bindEvent = () => {
    this.$timeline.on('mousedown', this.onMouseDown)
  }
}